(function() {
  // 将Vue组件定义为全局变量，供HTML页面使用
  window.CostWeightChangeChain = {
    template: `
      <div class="cost-weight-change-chain">
        <el-card class="search-card">
          <div slot="header">
            <span>成本单价变化链路查询</span>
          </div>
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="追踪事务ID">
              <el-input v-model="searchForm.ttid" placeholder="请输入追踪事务ID" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchChain">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card v-if="chainDetail" class="result-card" style="margin-top: 20px;">
          <div slot="header">
            <span>链路详情</span>
          </div>
          <div class="chain-summary">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">追踪事务ID:</div>
                  <div class="summary-value">{{ chainDetail.ttid }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">变化记录数:</div>
                  <div class="summary-value">{{ chainDetail.totalCount }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">涉及商品数:</div>
                  <div class="summary-value">{{ chainDetail.commodityCount }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">总变化金额:</div>
                  <div class="summary-value" :class="getChangeAmountClass(chainDetail.totalChangeAmount)">
                    {{ formatAmount(chainDetail.totalChangeAmount) }}
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="8">
                <div class="summary-item">
                  <div class="summary-label">首次变化时间:</div>
                  <div class="summary-value">{{ formatDate(chainDetail.firstChangeTime) }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="summary-item">
                  <div class="summary-label">最后变化时间:</div>
                  <div class="summary-value">{{ formatDate(chainDetail.lastChangeTime) }}</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="summary-item">
                  <div class="summary-label">持续时间:</div>
                  <div class="summary-value">{{ getDuration(chainDetail.firstChangeTime, chainDetail.lastChangeTime) }}</div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <div class="chain-details" style="margin-top: 20px;">
            <el-table :data="chainDetail.changes" style="width: 100%" border>
              <el-table-column prop="operateTime" label="操作时间" width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.operateTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="commodityName" label="商品名称" width="150"></el-table-column>
              <el-table-column label="变化类型" width="150">
                <template slot-scope="scope">
                  <el-tag :type="getChangeTypeTagType(scope.row.sourceType)">
                    {{ scope.row.getSourceTypeDescription }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="变化前成本" width="120" align="right">
                <template slot-scope="scope">
                  {{ formatAmount(scope.row.beforeCostWeight) }}
                </template>
              </el-table-column>
              <el-table-column label="变化后成本" width="120" align="right">
                <template slot-scope="scope">
                  {{ formatAmount(scope.row.afterCostWeight) }}
                </template>
              </el-table-column>
              <el-table-column label="变化差值" width="120" align="right">
                <template slot-scope="scope">
                  <span :class="getChangeAmountClass(scope.row.changeAmount)">
                    {{ formatAmount(scope.row.changeAmount) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="变化幅度" width="100" align="right">
                <template slot-scope="scope">
                  {{ scope.row.getChangeMagnitude }}
                </template>
              </el-table-column>
              <el-table-column label="变化方向" width="100" align="center">
                <template slot-scope="scope">
                  <el-tag :type="getChangeDirectionTagType(scope.row.changeAmount)">
                    {{ scope.row.getChangeDirection }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作人" width="100">
                <template slot-scope="scope">
                  {{ scope.row.operatorName }}
                </template>
              </el-table-column>
              <el-table-column label="源头订单" width="150">
                <template slot-scope="scope">
                  <div v-if="scope.row.sourceOrderNo">{{ scope.row.sourceOrderNo }}</div>
                  <div v-if="scope.row.getSourceOrderTypeDescription" style="font-size: 12px; color: #999;">
                    {{ scope.row.getSourceOrderTypeDescription }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="200">
                <template slot-scope="scope">
                  <div v-if="scope.row.isOrderCostRelated">
                    <strong>{{ scope.row.getOrderCostChangeDescription }}</strong>
                  </div>
                  <div v-else>
                    {{ scope.row.remark }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </div>
    `,
    name: 'CostWeightChangeChain',
    data: function() {
      return {
        searchForm: {
          ttid: ''
        },
        chainDetail: null
      }
    },
    methods: {
      searchChain: function() {
        if (!this.searchForm.ttid) {
          this.$message.warning('请输入追踪事务ID');
          return;
        }

        var self = this;
        this.$http({
          url: this.$http.adornUrl('/stock/costWeightChange/chain/detailByTtid'),
          method: 'get',
          params: this.$http.adornParams({
            'ttid': this.searchForm.ttid
          })
        }).then(function(response) {
          var data = response.data;
          if (data && data.code === 0) {
            self.chainDetail = data.data;
          } else {
            self.$message.error(data.msg || '查询失败');
          }
        }).catch(function() {
          self.$message.error('查询失败');
        });
      },
      resetSearch: function() {
        this.searchForm.ttid = '';
        this.chainDetail = null;
      },
      formatDate: function(date) {
        if (!date) return '';
        return this.$moment(date).format('YYYY-MM-DD HH:mm:ss');
      },
      formatAmount: function(amount) {
        if (amount === null || amount === undefined) return '0.000000';
        return parseFloat(amount).toFixed(6);
      },
      getChangeAmountClass: function(amount) {
        if (!amount) return '';
        var value = parseFloat(amount);
        if (value > 0) {
          return 'change-positive';
        } else if (value < 0) {
          return 'change-negative';
        }
        return '';
      },
      getChangeTypeTagType: function(sourceType) {
        switch (sourceType) {
          case 1: return 'primary';   // 订单价格修改
          case 2: return 'success';   // 入库调整
          case 3: return 'warning';   // 费用分摊
          case 4: return 'info';      // 重新包装
          case 5: return 'danger';    // 订单费用统计
          case 6: return 'danger';    // 订单费用影响检查
          default: return 'default';
        }
      },
      getChangeDirectionTagType: function(amount) {
        if (!amount) return 'info';
        var value = parseFloat(amount);
        if (value > 0) {
          return 'danger';  // 成本增加 - 红色
        } else if (value < 0) {
          return 'success'; // 成本减少 - 绿色
        }
        return 'info';      // 无变化 - 蓝色
      },
      getDuration: function(startTime, endTime) {
        if (!startTime || !endTime) return '';
        
        var start = new Date(startTime);
        var end = new Date(endTime);
        var diffMs = end - start;
        
        var diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
        var diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
        
        var result = '';
        if (diffDays > 0) result += diffDays + '天';
        if (diffHours > 0) result += diffHours + '小时';
        if (diffMinutes > 0) result += diffMinutes + '分钟';
        
        return result || '瞬间';
      }
    }
  };
})();